package cn.wolfcode.mq;

import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.web.msg.SeckillCodeMsg;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;


@Slf4j
@Component
@RocketMQMessageListener(
        consumerGroup = "MQCreateOrderListener",
        topic = MQConstant.ORDER_PEDDING_TOPIC
)
public class MQCreateOrderListener implements RocketMQListener<OrderMessage> {
    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void onMessage(OrderMessage message) {
        Long seckillId = message.getSeckillId();
        Integer time = message.getTime();
        String token = message.getToken();
        Long phone = message.getUserPhone();
        OrderMQResult orderMQResult = new OrderMQResult();
        orderMQResult.setSeckillId(seckillId);
        orderMQResult.setTime(time);
        orderMQResult.setToken(token);
        //定义消息的标签
        String tag = "";
        log.info("进入创建订单队列的消费者中");
        try {
            //int i = 1 / 0;
            String orderNo = orderInfoService.doSeckill(seckillId, time, phone);
            //成功:time,seckillId,token,orderNo
            orderMQResult.setOrderNo(orderNo);
            tag = MQConstant.ORDER_RESULT_SUCCESS_TAG;
            //往延时队列中发送消息  延迟第13级发送（延迟3秒）
            rocketMQTemplate.syncSend(MQConstant.ORDER_PAY_TIMEOUT_TOPIC,
                    MessageBuilder.withPayload(orderMQResult).build(),
                    3000000, MQConstant.ORDER_PAY_TIMEOUT_DELAY_LEVEL);
        } catch (Exception e) {
            e.getStackTrace();
            //失败:time,seckillId,token,code,msg
            orderMQResult.setCode(SeckillCodeMsg.SECKILL_ERROR.getCode());
            orderMQResult.setMsg(SeckillCodeMsg.SECKILL_ERROR.getMsg());
            tag = MQConstant.ORDER_RESULT_FAIL_TAG;
        }
        rocketMQTemplate.sendOneWay(MQConstant.ORDER_RESULT_TOPIC + ":" + tag, orderMQResult);
    }
}
